package chances.epg.api.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import chances.epg.commons.log.EpgLogFactory;

@Component
public class ApiLogInterceptor extends HandlerInterceptorAdapter{
	private Logger logger = EpgLogFactory.getSystemLogger();
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.debug("request path:{},header:[{}]",new Object[]{request.getRequestURL().toString(),this.getHeadersInfo(request)});
		super.afterCompletion(request, response, handler, ex);
	}
	
	private String getHeadersInfo(HttpServletRequest request) {
		String headersInfo = "";
	    Enumeration headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	    	if(headersInfo.length() > 0) {
	    		headersInfo += ",";
	    	}
	        String key = (String) headerNames.nextElement();
	        String value = request.getHeader(key);
	        headersInfo += key + ":" + value;
	    }
	    return headersInfo;
	  }
}
